[PHP] Invalid argument supplied for foreach()
Posted
by Roberto Aloi
on Stack Overflow
See other posts from Stack Overflow
or by Roberto Aloi
Published on 2010-04-13T13:48:46Z
Indexed on
2010/04/13
13:52 UTC
Read the original article
Hit count: 337
It often happens to me to handle data that can be either an array or a null variable and to feed some foreach
with these data.
$values = get_values();
foreach ($values as $value){
...
}
When you feed a foreach with data that are not an array, you get a warning:
Warning: Invalid argument supplied for foreach() in [...]
Assuming it's not possible to refactor the get_values()
function to always return an array (backward compatibility, not available source code, whatever other reason), I'm wondering which is the cleanest and most efficient way to avoid these warnings:
- Casting $values to array
- Initializing $values to array
- Wrapping the foreach with an if
- Other (please suggest)
© Stack Overflow or respective owner